package com.sls.game.service.impl;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.ServerDateAndTime;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.GoodsInfoManageDAO;
import com.sls.game.dao.GoodsSupplyManageDAO;
import com.sls.game.dao.PriceTemplateDAO;
import com.sls.game.dao.SpecialPriceSystemDAO;
import com.sls.game.page.Pagination;
import com.sls.game.pojo.GoodsManageInfo;
import com.sls.game.pojo.GoodsSupplyManageInfo;
import com.sls.game.pojo.PriceTemplateInfo;
import com.sls.game.pojo.SpecialPriceSystemInfo;
import com.sls.game.querybean.SpecialPriceSystemQuery;
import com.sls.game.service.SpecialPriceSystemService;

@Service("specialPriceSystemService")
public class SpecialPriceSystemServiceImpl implements SpecialPriceSystemService {
	private static Logger log = Logger
			.getLogger(SpecialPriceSystemServiceImpl.class);
	@Resource(name = "specialPriceSystemDAO")
	private SpecialPriceSystemDAO specialPriceSystemDAO;
	@Resource(name = "goodsInfoManageDAO")
	private GoodsInfoManageDAO goodsInfoManageDAO;
	@Resource(name = "goodsSupplyManageDAO")
	private GoodsSupplyManageDAO goodsSupplyManageDAO;
	@Resource(name = "priceTemplateDAO")
	private PriceTemplateDAO priceTemplateDAO;

	private Gson gson;

	public SpecialPriceSystemServiceImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public String save(String body, Head head) throws ServerDisponseException {
		final SpecialPriceSystemInfo priceInfo = gson.fromJson(body,
				SpecialPriceSystemInfo.class);
		this.validate(priceInfo);
		this.validateData(priceInfo);
		new Thread(new Runnable() {
			@Override
			public void run() {
				List<GoodsManageInfo> gmInfoList = null;
				gmInfoList = goodsInfoManageDAO.queryAllGoodsId();
				if (gmInfoList != null && gmInfoList.size() > 0) {
					for (GoodsManageInfo gmInfo : gmInfoList) {
						// 商品编号
						String goodsId = gmInfo.getGoodsId();
						// 商品名称
						String goodsName = gmInfo.getGoodsName();
						// 品牌编号
						String brandId = gmInfo.getGoodsCategoryId();
						// 品牌名称
						String brandName = gmInfo.getBrandName();
						String templateCode = priceTemplateDAO
								.queryTemplateCodeByName(priceInfo
										.getTemplateName());
						priceInfo.setGoodsId(goodsId);
						priceInfo.setTemplateCode(templateCode);
						SpecialPriceSystemInfo info = specialPriceSystemDAO
								.queryPriceSystemByGoodsIdAndTemplateCode(priceInfo);
						if (info != null) {
							continue;
						}
						GoodsSupplyManageInfo supllyInfo = new GoodsSupplyManageInfo();
						supllyInfo.setGoodsId(goodsId);
						String highPrice = goodsSupplyManageDAO
								.queryHighInPrice(supllyInfo);
						int highInPrice = 0;
						try {
							highInPrice = Integer.parseInt(highPrice);
						} catch (NumberFormatException e) {
							continue;
						}
						int discount = priceInfo.getPriceRatio();
						double d = highInPrice * discount * 1.0 / 1000;
						long l = Math.round(d);
						Long lo = new Long(l);
						int discountPrice = lo.intValue();
						highInPrice = highInPrice + discountPrice;

						priceInfo.setInPrice(highInPrice);
						priceInfo.setId(UUID.randomUUID().toString());
						priceInfo.setGoodsName(goodsName);
						priceInfo.setBrandId(brandId);
						priceInfo.setBrandName(brandName);
						if (info == null) {
							insert(priceInfo);
						}
					}
				}
			}
		}).start();
		return null;
	}

	@Override
	public void saveSetPrice(String body, Head head)
			throws ServerDisponseException {
		SpecialPriceSystemInfo priceInfo = gson.fromJson(body,
				SpecialPriceSystemInfo.class);
		this.validate(priceInfo);
		this.validateData(priceInfo);
		String templateCode = priceTemplateDAO
				.queryTemplateCodeByName(priceInfo.getTemplateName());
		priceInfo.setGoodsId(priceInfo.getGoodsId());
		priceInfo.setTemplateCode(templateCode);
		SpecialPriceSystemInfo info = specialPriceSystemDAO
				.queryPriceSystemByGoodsIdAndTemplateCode(priceInfo);
		if (info != null) {
			throw new ServerDisponseException("PRICE_EXIST", "价格模板已设置，若价格有变动，请修改价格即可");
		}
		GoodsSupplyManageInfo supllyInfo = new GoodsSupplyManageInfo();
		supllyInfo.setGoodsId(priceInfo.getGoodsId());
		String highPrice = goodsSupplyManageDAO.queryHighInPrice(supllyInfo);
		if(StringUtils.isBlank(highPrice)){
			throw new ServerDisponseException("NO_SUPPLY", "请先添加供应信息");
		}
		int highInPrice = Integer.parseInt(highPrice);
		int salePrice = priceInfo.getInPrice();
		if (salePrice < highInPrice) {
			throw new ServerDisponseException("PRICE_ERROR", "模板售价不能低于最高进价");
		}
		priceInfo.setId(UUID.randomUUID().toString());
		insert(priceInfo);
	}

	/**
	 * 插入数据库
	 * 
	 * @param head
	 * @param priceInfo
	 */
	private void insert(SpecialPriceSystemInfo priceInfo) {
		try {
			priceInfo.setInsertTime(ServerDateAndTime.getNowDateTimeOfFormat());
			specialPriceSystemDAO.insert(priceInfo);
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	@Override
	public String update(String body, Head head) throws ServerDisponseException {
		SpecialPriceSystemInfo priceInfo = gson.fromJson(body,
				SpecialPriceSystemInfo.class);
		validate(priceInfo);
		boolean flag = this.validateData(priceInfo);
		if (flag) {
			try {
				priceInfo.setModifyTime(ServerDateAndTime
						.getNowDateTimeOfFormat());
				specialPriceSystemDAO.update(priceInfo);
				return null;
			} catch (Exception e) {
				log.error(e.toString(), e);
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
			}
		}
		return null;
	}

	@Override
	public String delete(String body, Head head) throws ServerDisponseException {
		String id = gson.fromJson(body, String.class);
		if (StringUtils.isEmpty(id)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getDescription());
		}
		try {
			specialPriceSystemDAO.delete(id);
			return null;
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	@Override
	public String queryPriceSystem(String body, Head head)
			throws ServerDisponseException {
		SpecialPriceSystemQuery priceQuery = gson.fromJson(body,
				SpecialPriceSystemQuery.class);
		validate(priceQuery);
		try {
			Pagination<SpecialPriceSystemInfo> page = specialPriceSystemDAO
					.querySpecialPriceSystem(priceQuery);
			String resultBody = null;
			if (page != null) {
				resultBody = gson.toJson(page);
			}
			return resultBody;
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	@Override
	public String queryPriceSystemByGoodsIdAndTemplateCode(String body,
			Head head) throws ServerDisponseException {
		SpecialPriceSystemInfo priceInfo = gson.fromJson(body,
				SpecialPriceSystemInfo.class);
		validate(priceInfo);
		if (StringUtils.isEmpty(priceInfo.getGoodsId())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.GOODS_ID_EMPTY.getCode(),
					ExceptionCodeDes.GOODS_ID_EMPTY.getDescription());
		}
		if (StringUtils.isEmpty(priceInfo.getTemplateCode())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.TEMPLATE_ID_EMPTY.getCode(),
					ExceptionCodeDes.TEMPLATE_ID_EMPTY.getDescription());
		}
		try {
			priceInfo = specialPriceSystemDAO
					.queryPriceSystemByGoodsIdAndTemplateCode(priceInfo);
		} catch (Exception e) {
			log.error(e.toString(), e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
		if (priceInfo != null) {
			String resultBody = gson.toJson(priceInfo);
			return resultBody;
		} else {
			throw new ServerDisponseException(
					ExceptionCodeDes.PRICE_INFO_NOT_EXIST.getCode(),
					ExceptionCodeDes.PRICE_INFO_NOT_EXIST.getDescription());
		}
	}

	/**
	 * 数据校验
	 * 
	 * @param info
	 * @return
	 * @throws ServerDisponseException
	 */
	private boolean validateData(SpecialPriceSystemInfo info)
			throws ServerDisponseException {
		boolean result = false;
		if (StringUtils.isEmpty(info.getTemplateName())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.TEMPLATE_NAME_EMPTY.getCode(),
					ExceptionCodeDes.TEMPLATE_NAME_EMPTY.getDescription());
		} else if (StringUtils.isEmpty(info.getOperator())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.OPERATOR_NO_NULL.getCode(),
					ExceptionCodeDes.OPERATOR_NO_NULL.getDescription());
		} else {
			result = true;
		}

		return result;
	}

	/**
	 * 校验是否为null
	 * 
	 * @param priceInfo
	 */
	private void validate(Object obj) throws ServerDisponseException {
		if (obj == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getDescription());
		}
	}

	@Override
	public String queryPriceSystemByGoodsId(String body, Head head)
			throws ServerDisponseException {
		String goodsId = gson.fromJson(body, String.class);
		validate(goodsId);
		List<SpecialPriceSystemInfo> list = this.specialPriceSystemDAO
				.queryPriceSystemsByGoodsId(goodsId);
		if (list == null || list.isEmpty()) {
			return "true";
		} else {
			throw new ServerDisponseException(
					ExceptionCodeDes.PRICE_TEMPLATE_EXIST.getCode(),
					ExceptionCodeDes.PRICE_TEMPLATE_EXIST.getDescription());
		}
	}

	/**
	 * 查询模板信息
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryTemplateInfo(String body, Head head)
			throws ServerDisponseException {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		List<SpecialPriceSystemInfo> list = null;
		list = specialPriceSystemDAO.queryTemplateInfo();
		if (list != null && list.size() > 0) {
			String resultBody = null;
			resultBody = gson.toJson(list);
			return resultBody;
		}

		return null;
	}

	@Override
	public void insertCopyTemplateInfo(String body, Head head)
			throws ServerDisponseException {
		SpecialPriceSystemInfo priceInfo = gson.fromJson(body,
				SpecialPriceSystemInfo.class);
		validate(priceInfo);
		final String templateCode = priceInfo.getTemplateCode();
		final String newTemplateCode = priceInfo.getNewTemplateCode();
		PriceTemplateInfo tempInfo = this.priceTemplateDAO
				.queryTemplateByCode(newTemplateCode);
		final String newTemplateName = tempInfo.getTemplateName();

		final String operator = priceInfo.getOperator();
		if (StringUtils.isEmpty(templateCode)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.TEMPLATE_ID_EMPTY.getCode(),
					ExceptionCodeDes.TEMPLATE_ID_EMPTY.getDescription());
		}
		if (StringUtils.isEmpty(newTemplateCode)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.TEMPLATE_ID_EMPTY.getCode(),
					ExceptionCodeDes.TEMPLATE_ID_EMPTY.getDescription());
		}
		if (StringUtils.isEmpty(operator)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.OPERATOR_NO_NULL.getCode(),
					ExceptionCodeDes.OPERATOR_NO_NULL.getDescription());
		}
		if (StringUtils.isEmpty(newTemplateName)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.TEMPLATE_NAME_EMPTY.getCode(),
					ExceptionCodeDes.TEMPLATE_NAME_EMPTY.getDescription());
		}
		new Thread(new Runnable() {
			@Override
			public void run() {

				List<SpecialPriceSystemInfo> list = specialPriceSystemDAO
						.queryTemplateInfoByTemplateCode(templateCode);
				if (list != null && !list.isEmpty()) {
					for (SpecialPriceSystemInfo info : list) {
						info.setId(UUID.randomUUID().toString());
						info.setTemplateCode(newTemplateCode);
						info.setTemplateName(newTemplateName);
						info.setOperator(operator);
						insert(info);
					}
				}
			}
		}).start();
	}

	@Override
	public List<SpecialPriceSystemInfo> queryPriceTemplateInfoList(Head head)
			throws ServerDisponseException {
		List<SpecialPriceSystemInfo> list = this.specialPriceSystemDAO
				.queryPriceTemplateInfoList();
		return list;
	}

}
